<!--
 @description 自定义导航
 @fileName index.vue
 @author zengqiongying
 @created 2023/08/24 20:27:48
-->
<template>
  <div class="qup-full-page">
    <template v-if="showPageType==='config'">
      <config-page :page-show.sync="showPageType" :page-data="activeRowData" />
    </template>
    <template v-if="showPageType==='detail'">
      <config-page :page-show.sync="showPageType" :page-data="activeRowData" readonly />
    </template>
    <div v-show="!showPageType">
      <checkFilter
        title="状态"
        :filter-data="[
          {value:1,label:'启用'},
          {value:0,label:'停用'}
        ]"
        property="enableFlag"
        @changeFilter="changeFilterState"
      />
      <table-box
        ref="refTable"
        :selected-arry.sync="tableSelected"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :off-set="-10"
        table-row-key="id"
        show-index
        :show-custom-collect="false"
        :show-custom-combine="false"
        :show-custom-setting="false"
        :setting-auto-request="false"
        @btnOperate="btnOperate"
      />

      <EditBasic
        v-if="showEditBasic"
        ref="refEditPage"
        :visible.sync="showEditBasic"
        :detail="activeRowData"
        @success="handleBasicSuccess"
      />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { delTabDefine, getDetail, updatState } from '@/api/tabDefine'
import checkFilter from '@/components/checkFilter'
import ConfigPage from './Config'
import EditBasic from './EditBasic'
export default {
  name: 'TabDefineList',
  components: { EditBasic, checkFilter, ConfigPage },
  props: {},
  data() {
    const that = this
    return {
      showPageType: '', // 显示导航类型：floor 配置导航， detail详情
      showEditBasic: false, // 是否编辑基础信息
      activeRowData: '', // 当前选中行数据
      tableSelected: [], // 当前所选中表格行数据
      defaultFilter: [{ id: 'type', property: 'type', operator: 'in', value: '[1,2,3]' }], // 必传查询条件
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/v2TabDefine/page`,
        onlySearchBar: false,
        tabIndex: 0,
        pageSize: 20,
        sort: 'lastUpdateTime',
        order: 'desc',
        setting: [
          {
            prop: 'name',
            label: '导航名称',
            minWidth: 150,
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleToDetail
          },
          {
            prop: 'picUrl',
            label: '导航图片',
            width: 120,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.picUrl || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cate_img'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'type',
            label: '类型',
            width: 80,
            type: 'select',
            propEnum: {
              list: [
                { dictCode: '1', dictName: '导航' },
                { dictCode: '2', dictName: '分类' },
                { dictCode: '3', dictName: '目录' }
              ]
            }
          },
          {
            prop: 'showLevel',
            label: '层级',
            width: 80,
            type: 'select',
            propEnum: {
              list: [
                { dictCode: '1', dictName: '一层' },
                { dictCode: '2', dictName: '二层' },
                { dictCode: '3', dictName: '三层' },
                { dictCode: '4', dictName: '四层' }
              ]
            }
          },
          {
            prop: 'enableFlag',
            label: '状态',
            width: 100,
            type: 'hidden',
            formatData: ({ enableFlag }) => {
              return Number(enableFlag || 0) === 1 ? '启用' : '停用'
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150,
            type: 'text'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ createTime }) => {
              return parseTime(createTime)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150,
            type: 'text'
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'date',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          }],
        btnList: !this.isProduction ? [
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '配置导航',
            optCode: 'config',
            outerFlag: true
          },
          {
            buttonName: '删除',
            optCode: 'del',
            outerFlag: true
          },
          {
            buttonName: '启用',
            optCode: 'enable',
            outerFlag: true
          },
          {
            buttonName: '停用',
            optCode: 'disable',
            outerFlag: true
          }] : null
      },
      sorting: false,
      showEdit: false,
      buttons: [],
      detailData: {}
    }
  },
  computed: {},
  watch: {
    showPageType(val, oldVal) {
      if (!val) {
        this.activeRowData = ''
      }
    }
  },
  created() {
    this.otherFilters = [...this.defaultFilter]
  },
  methods: {
    changeFilterState(val) {
      this.otherFilters = [...this.defaultFilter, ...val]
      this.$nextTick(() => {
        this.refreshTable(true)
      })
    },
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'config':
          if (!this.singleJudge(this.tableSelected, '配置导航', true)) {
            return
          }
          this.handleConfig(this.tableSelected[0])
          break
        case 'del':
          if (!this.singleJudge(this.tableSelected, '删除', true)) {
            return
          }
          this.handleDelete()
          break
        case 'disable':
          if (!this.singleJudge(this.tableSelected, '停用', true)) {
            return
          }
          this.handleChangeStatus(0) // state 1：启用  0：停用
          break
        case 'enable':
          if (!this.singleJudge(this.tableSelected, '启用', true)) {
            return
          }
          this.handleChangeStatus(1) // state 1：启用  0：停用
          break
        default:
          break
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
      })
    },
    // 详情跳转
    handleToDetail(row) {
      if (!row.id) {
        this.$message.warning('数据异常')
        return
      }
      if (this.loading) return
      this.loading = true
      getDetail(row.id).then(res => {
        this.loading = false
        if (res.data && res.data.id) {
          this.activeRowData = res.data
          this.$nextTick(() => {
            this.showPageType = 'detail'
          })
        } else {
          this.$message.warning('数据异常！无法查看详情')
        }
      }).catch(() => {
        this.loading = false
      })
    },
    // 配置导航
    handleConfig(row) {
      this.activeRowData = row
      this.$nextTick(() => {
        this.showPageType = 'config'
      })
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      this.activeRowData = row || ''
      this.$nextTick(() => {
        this.showEditBasic = true
      })
    },
    handleBasicSuccess(res) {
      const data = res.data
      const goConfig = res.goConfig // 是否前往配置
      this.refreshTable(!!data.id)
      if (goConfig) {
        this.showPageType = 'config'
        this.activeRowData = data
        this.tableSelected = [data]
      }
    },
    /**
     * 处理启用/停用
     * @param {Number} state 1 启用 0 停用
     * @param {String} id
    */
    handleChangeStatus(state) {
      const tmpArr = this.tableSelected.filter(row => row.enableFlag === state)
      if (tmpArr.length > 0) {
        this.$message.warning(`当前所选导航包含${state ? '启用' : '停用'}状态，请勿重复操作`)
        return
      }
      this.$confirm(`此操作将当前所选导航${state ? '启用' : '停用'},是否继续`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.tableSelected[0].id
        const params = { id, state }
        updatState(params).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '操作成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      })
    },
    // 删除处理
    handleDelete() {
      this.$confirm('此操作将永久删除该自定义导航, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.tableSelected[0].id
        delTabDefine(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    }
  }
}
</script>
<style lang='scss' scoped>
  .my-txt-btn{
    padding: 0 !important;
  }
 .cate_img{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      width: auto;
      height: 40px;
      // object-fit: cover;
      object-fit: contain;
    }
  }
</style>
